package com.yc.demo.d0304;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

@WebFilter(filterName = "LoginFilter",
        value = {"/day0304/hello.html","/day0304/check.html"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("LoginFilter 初始化");
    }

    public void destroy() {
        System.out.println("LoginFilter 销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
       //判断是否登录=》在会话中查找 loginedUser属性
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();;
        if (session.getAttribute("loginedUser") == null){
            //说明未登录
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //获取应用上下文对象
            ServletContext servletContext = httpServletRequest.getServletContext();
            //contextPath => /webdemo_war_example
            String contextPath = servletContext.getContextPath();
            //使用绝对路径
            //编码
            String url = contextPath + "/day0303/" + URLEncoder.encode("验证码", "utf-8") + ".html";
            //跳转登录页
            httpServletResponse.sendRedirect(url);

            //保存当前访问的页面地址
            String requestURL = httpServletRequest.getRequestURI();
            System.out.println("requestURL = " + requestURL);
            //将该地址保存到会话
            session.setAttribute("requestURL", requestURL);
            //返回,不允许访问目标资源,不能执行 chain.doFilter....
            return;

        }
        System.out.println("LoginFilter 执行过滤（前）");
        chain.doFilter(request, response);
        System.out.println("LoginFilter 执行过滤（后）");
    }

}
